package nige.d3.test;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;

public class Experience2 extends JFrame implements 
		MouseMotionListener {
	RenderingThread renderingThread = new RenderingThread();
	Graphics buffer;
	Image image; 
	boolean drawing = false;
	int lastX = -1;
	int lastY = -1;
	
	public Experience2(){
		setSize( 400, 400 );
		setVisible(true);
		addMouseMotionListener(this);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		renderingThread.start();
	}
	
	public void update(Graphics g){
		paint(g);
	}
	
	public void paint(Graphics g){
		if(buffer==null){
			image = createImage(400,400);
			buffer = image.getGraphics();
			buffer.setColor(Color.white);
			buffer.fillRect( 0, 0, 400, 400 );
		}
		g.drawImage(image, 0, 0, this);
	}
	
	class RenderingThread extends Thread {
		public void run(){
			while(true){
				try {
					repaint(); 
					sleep(20);
				}
				catch (Exception e) {
				} 
			}
		}
	}
	
	public static void main(String[] args){
		new Experience2();
	}

	public void mouseDragged(MouseEvent e) {
		System.out.println(e.getModifiers());
		if(buffer!=null) {
			if(e.getModifiers()==16) {
				buffer.setColor(new Color(0,0,0));
			}
			if(e.getModifiers()==4) {
				buffer.setColor(new Color(255,255,255));
			}
			if(lastX>0) {
				buffer.drawLine(lastX,lastY,(int)e.getPoint().getX(),
						(int)e.getPoint().getY());
			}
			lastX = (int)e.getPoint().getX();
			lastY = (int)e.getPoint().getY();
		}
	}

	public void mouseMoved(MouseEvent e) {
		lastX = -1;
	}
}
